const {request} = require("./request")
const DateUtils = require("./date");
const tunnel = require('tunnel')
const {promises: fs} = require("fs");
const path = require('path');
const dataDir = path.dirname(path.dirname(path.dirname(__filename)))
class ProxyUtils{
    originProxy = null
    enable = true
    cacheFile = dataDir + "/data/proxy.txt"
    constructor(url) {
        this.url = url
    }

    async setProxyOptions(options){
        await this.getProxy()
        if(this.originProxy){
            const tunnelProxy = tunnel.httpsOverHttp({
                proxy: {
                    host: this.originProxy.ip,
                    port: this.originProxy.port,
                },
            });
            options.proxy = false
            options.httpsAgent = tunnelProxy
            // console.log(options)
        }


    }

    async getProxy(){
        if(!this.enable){
            return null
        }

        if(!this.originProxy || !this.checkProxy(this.originProxy)){
            this.originProxy = await this.flashProxy()
        }

        if(this.originProxy){
            return this.formatProxy(this.originProxy)
        }
        return null
    }
    // 刷新代理
    async flashProxy(){
        let proxy = await this.getCacheProxy()
        if(proxy && this.checkProxy(proxy)){
            return proxy
        }
        let ret = await request({
            url: this.url,
            method: 'get'
        })
        if(!ret || !ret['data'][0]){
            this.enable = false
            return null
        }
        await this.setCacheProxy(ret['data'][0])
        return ret['data'][0]
    }

    /**
     *
     * @param  originProxy Object {ip:xxx, port:xxx, end_time:xxx}
     */
    checkProxy(originProxy){
        return DateUtils.diifTime(originProxy.end_time) > 2000;
    }
    formatProxy(originProxy){
        return {
            // protocol: 'https',
            host: originProxy.ip,
            port: originProxy.port,
        }
    }

    async getCacheProxy(){
        try {
            const result = await fs.access(this.cacheFile);
            if (result) {
                let content = await fs.readFile(this.cacheFile, 'utf8');
                return JSON.parse(content)
            } else {
                return false;
            }
        }catch (e){
            console.log("文件不存在")
            return false
        }
    }

    async setCacheProxy(proxy){
        let content = JSON.stringify(proxy)
        await fs.writeFile(this.cacheFile, content, err => {
            if (err) {
                console.error(err);
            }
        });
    }
}

module.exports = ProxyUtils